package thread.lockpackage;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 使用Lock实现线程间同步
 */
public class MyLock {


    public static void main(String[] args) throws InterruptedException {
        Lock lock = new ReentrantLock(false);
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                lockInterruptible(lock);
            }
        }, "thread1");

        lock.lock();;
        thread.start();
        Thread.sleep(1000);
        thread.interrupt();
        lock.unlock();

//        new Thread(() -> {
//            try {
//                doLock(lock);
//            } catch (InterruptedException e) {
//                throw new RuntimeException(e);
//            }
//        }, "thread2").start();
//        new Thread(() -> {
//            try {
//                doLock(lock);
//            } catch (InterruptedException e) {
//                throw new RuntimeException(e);
//            }
//        }, "thread3").start();
    }

    private static void doLock(Lock lock) throws InterruptedException {
        boolean result = lock.tryLock(1, TimeUnit.SECONDS);
        System.out.println(result);
        if (result) {
            Thread.sleep(2000);
            for (int i = 0; i <= 5; i++) {
                System.out.println(Thread.currentThread().getName() + " ; " + i);
            }
            System.out.println();
            lock.unlock();
        }

    }

    private static void tryLock(Lock lock) {
        if (lock.tryLock()) {
            for (int i = 0; i <= 5; i++) {
                System.out.println(Thread.currentThread().getName() + " ; " + i);
            }
            System.out.println();
            lock.unlock();
        }
    }

    private static void lockInterruptible(Lock lock) {
        try {
           lock.lockInterruptibly();
           try {
               Thread.sleep(1000);
               for (int i = 0; i <= 5; i++) {
                   System.out.println(Thread.currentThread().getName() + " ; " + i);
               }
           }finally {
               lock.unlock();
           }
        } catch (InterruptedException e) {
            System.out.println("线程被中断，退出锁等待！"); // 立即响应中断
        }
    }

}

